package com.example.gokchinesefoodmappcdev.filter;

import com.example.gokchinesefoodmappcdev.entity.SysMenu;
import com.example.gokchinesefoodmappcdev.entity.SysRole;
import com.example.gokchinesefoodmappcdev.service.MenuService;
import com.example.gokchinesefoodmappcdev.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;

/*
* 自定义权限验证的规则
* */
@Component
public class MerchantSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Autowired
    MenuService menuService;

    @Autowired
    RoleService roleService;

    public final static String ROLE_PREFIX = "ROLE_";
    AntPathMatcher antPathMatcher=new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        HttpServletRequest request=((FilterInvocation)object).getRequest();

        //1.获取用户的请求，比如：/user/addUser
        String requestURI = request.getRequestURI();
        //2.获取权限表中的所有menu_url
        List<SysMenu> allMenus = menuService.getAllMenus();

        boolean flag=true;
        //3.遍历menu权限集合，找出 用户提交的requestURI  与之对应的menu_url
        for (SysMenu menu : allMenus) {
            if(menu.getUrl()==null || menu.getUrl()==""){
                continue;
            }
            if(antPathMatcher.match(menu.getUrl(),requestURI)){
                flag=false;
                //4.如果匹配，则依据menu表，找到能执行该请求地址的  角色集合
                    List<SysRole> roles = roleService.findRolesByMenuId(Math.toIntExact(menu.getMenuId()));
                //5. 将得到的角色名字的集合放入SecurityConfig中的一个List集合中，Spring Security会自行匹配
                String[] roleNames = new String[roles.size()];

                for (int i = 0; i < roleNames.length; i++) {
                    roleNames[i] = ROLE_PREFIX + roles.get(i).getRoleName();
                }

                return SecurityConfig.createList(roleNames);
            }
        }
        if(flag){
            return SecurityConfig.createList(ROLE_PREFIX+"普通用户");
        }
        return SecurityConfig.createList();
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz);
    }
}
